<template>
  <div>
    <p><a href="#/register">还没有账号，要注册</a></p>
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import qs from "qs";
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      username: "13500000000",
      password: "123",
      flag: true
    };
  },
  methods: {
    async onSubmit() {
      var obj = { mobile: this.username, pwd: this.password };

      //调用接口
      let { data: res } = await this.$http.get(
        "https://api.it120.cc/small4/user/m/login?deviceId=007&deviceName=monkey&" +
          qs.stringify(obj)
      );
      console.log(res);
      //判断
      if (res.msg == "success") {
        //存储token
        this.setToken(res.data.token);
        //提示
        this.$toast.success("登录成功");
        //跳转
        if (this.flag) {
          this.$router.push("/home");
        } else {
          this.$router.go(-1);
        }
      } else {
        this.$toast.fail(res.msg);
      }
    },
    ...mapMutations(["setToken"])
  },
  computed: {
    ...mapState(["token"])
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (from.path != "/my") {
        vm.flag = false;
      }
    });
  }
};
</script>

<style>
</style>